import {getRouters} from "@/api/menu";
import router from '@/router'
import type {RouteRecordRaw} from "vue-router";
import Layout from "@/components/Layout";
import User from "@/views/user/User.vue";

const permission = defineStore('permission', {
    // 推荐使用 完整类型推断的箭头函数
    state: () => ({
        routes: [],
        addRoutes: [],
        defaultRoutes: [],
        topbarRouters: [],
        sidebarRouters: []
    }),
    actions: {
        // 生成路由
        async GenerateRoutes() {
            // 向后端请求路由数据
            const res = await getRouters();
            //侧边栏路由
            // const sdata = dfs(res.data);
            //router
            // const rewriteRoutes = dfs(res.data);
         //   console.log(rewriteRoutes)
            // rewriteRoutes.forEach(item => {
            //     router.addRoute(item) // 动态添加可访问路由表
            // })
        }
    },
    getters: {},
})


export const loadView = (view) => {
    return (resolve) => require([`@/views/${view}`], resolve)
}


// 处理路由列表
function dfs(routes: any) : Array<RouteRecordRaw> {

    if (routes == undefined || routes == null || routes.length == 0)
        return [];
    const router = new Array<RouteRecordRaw>;

    for (let i = 0; i < routes.length; i++) {
        const t = <RouteRecordRaw>{...routes[i]};
        setComponent(t);
        t.children = dfs(t.children);
        router.push(t);
    }
    return router;
}

function setComponent(route) {
    if (route.component) {
        // Layout ParentView 组件特殊处理
        if (route.component === 'Layout') {
            route.component = () => import('@/components/Layout/index.vue')
        } else if (route.component === 'ParentView') {
            route.component = () => import('@/components/ParentView/index.vue')
        } else if (route.component === 'InnerLink') {
            route.component = () => import('@/components/InnerLink/index.vue')
        } else {
            route.component = loadView(route.component)
        }
    }

}

export default permission
